package com.cloudcc.mobile.view.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;

import checkauto.camera.com.BucardRunner;
import checkauto.camera.com.CameraActivity;
import checkauto.camera.com.Devcode;
import checkauto.camera.com.ImageChooser;
import checkauto.camera.com.RecogOpera;
import checkauto.camera.com.util.CheckPermission;
import checkauto.camera.com.util.PermissionActivity;
import checkauto.camera.com.util.ReturnData;
import checkauto.camera.com.util.Utils;

//选择文件操作类
public class SelectPictureNamecordActivity extends BaseActivity implements
        OnClickListener, ReturnData.CallData {

    private LinearLayout dialogLayout;
    private TextView takePhotoBtn, pickPhotoBtn;
    private Button cancelBtn;

    int zoomin,zoomout;

    private CheckPermission checkPermission;

    private String devcode = Devcode.devcode;// 项目授权开发码

    private String selectPath;

    private String codes;
    private boolean kehuqx, contastqx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);
            dialogLayout.setOnClickListener(this);
            takePhotoBtn = (TextView) findViewById(R.id.btn_take_photo);
            takePhotoBtn.setOnClickListener(this);
            pickPhotoBtn = (TextView) findViewById(R.id.btn_pick_photo);
            pickPhotoBtn.setOnClickListener(this);
            cancelBtn = (Button) findViewById(R.id.btn_cancel);
            cancelBtn.setOnClickListener(this);
        } catch (Exception e) {
            Tools.handle(e);
        }
        codes = getIntent().getStringExtra("codes");
        kehuqx = getIntent().getBooleanExtra("kehuqx",true);
        contastqx = getIntent().getBooleanExtra("contastqx",true);
        zoomin = this.getResources().getIdentifier("zoomin", "anim",
                this.getPackageName());
        zoomout = this.getResources().getIdentifier("zoomout", "anim",
                this.getPackageName());


        ReturnData.getDefault().setCallData(this);
        checkPermission = new CheckPermission(this);

    }

    @Override
    public int getLayoutId() {
        return R.layout.add_pic_layout;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_layout:
                finish();
                break;
            case R.id.btn_take_photo:
                goCream(true);//true：自动拍照  false：手动
                break;
            case R.id.btn_pick_photo:
                goPhoto();
                break;
            default:
                finish();
                break;
        }
    }

    /**
     * 直接调用相机界面
     */
    private void goCream(Boolean type) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission.permissionSet(ImageChooser.PERMISSION)) {
                PermissionActivity.startActivityForResult(SelectPictureNamecordActivity.this, 0, devcode, true, true, ImageChooser.PERMISSION);
            } else {
                Intent intent = new Intent();
                intent.setClass(SelectPictureNamecordActivity.this, CameraActivity.class);
                intent.putExtra("devcode", devcode);
                intent.putExtra("autocamera", type);
//                SelectPictureNamecordActivity.this.finish();
                startActivity(intent);
                overridePendingTransition(zoomin, zoomout);
            }
        } else {
            Intent intent = new Intent();
            intent.setClass(SelectPictureNamecordActivity.this, CameraActivity.class);
            intent.putExtra("devcode", devcode);
            intent.putExtra("autocamera", type);
//            SelectPictureNamecordActivity.this.finish();
            startActivity(intent);
            overridePendingTransition(zoomin, zoomout);
        }
        finish();
    }

    private void goPhoto() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission.permissionSet(ImageChooser.PERMISSION)) {
                PermissionActivity.startActivityForResult(SelectPictureNamecordActivity.this, 0, devcode, true, false, ImageChooser.PERMISSION);
            } else {
                Intent innerIntentX = new Intent(Intent.ACTION_GET_CONTENT);
                innerIntentX.addCategory(Intent.CATEGORY_OPENABLE);
                innerIntentX.setType("image/*");
                Intent wrapperIntentX = Intent.createChooser(innerIntentX,
                        "Select Picture");
                startActivityForResult(wrapperIntentX, 9);
                overridePendingTransition(zoomin, zoomout);
            }
        } else {
            Intent innerIntentX = new Intent(Intent.ACTION_GET_CONTENT);
            innerIntentX.addCategory(Intent.CATEGORY_OPENABLE);
            innerIntentX.setType("image/*");
            Intent wrapperIntentX = Intent.createChooser(innerIntentX,
                    "Select Picture");
            startActivityForResult(wrapperIntentX, 9);
            overridePendingTransition(zoomin, zoomout);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 9 && resultCode == Activity.RESULT_OK) {
            // 选择后识别
            Bitmap bitmap;
            String zipPicPath = "";
            Uri uri = data.getData();
            selectPath = Utils.getPath(getApplicationContext(), uri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inSampleSize = 2;
            bitmap = BitmapFactory.decodeFile(selectPath, options);
            //System.out.println("选择的图片的路径为:" + selectPath);
            if (bitmap == null || selectPath.endsWith(".png")) {
                Toast.makeText(getApplicationContext(), "图片损坏或格式不正确!", Toast.LENGTH_SHORT).show();
            } else {
                //  System.out.println("选择图片的的宽度为:" + bitmap.getWidth() + "选择图片的高度为:" + bitmap.getHeight());
                if (bitmap.getWidth() < bitmap.getHeight()) {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(270);
                    bitmap = Bitmap
                            .createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                                    bitmap.getHeight(), matrix, true);
                    /* 创建文件 */
                    File dir = new File(CameraActivity.path);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    BufferedOutputStream bos;
                    zipPicPath = CameraActivity.path + Utils.pictureName()
                            + ".jpg";
                    try {
                        bos = new BufferedOutputStream(new FileOutputStream(
                                zipPicPath));
                        /* 采用压缩转档方法 */
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
						/* 调用flush()方法，更新BufferStream */
                        bos.flush();
						/* 结束OutputStream */
                        bos.close();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                } else {
                    zipPicPath = selectPath;
                }
                if (bitmap != null) {
                    if (!bitmap.isRecycled()) {
                        bitmap.recycle();
                        System.gc();
                    }
                    bitmap = null;
                }
                RecogOpera recogUtils = new RecogOpera(1, SelectPictureNamecordActivity.this);
                recogUtils.startActivityRecog(null, null, 0, 0, zipPicPath);
            }
        } else if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            // 拍照后存图片
            boolean go = false;
            if (selectPath == null) {
                selectPath = getLatestImage();
                File file = new File(selectPath);
                if (file.exists()) {
                    go = true;
                } else {
                }
            } else {
                go = true;
            }
            if (go) {
                // 跳转
                File file = new File(selectPath);
                Bitmap source = BitmapFactory.decodeFile(selectPath);
                Bitmap bmp = Bitmap.createScaledBitmap(source, 1280, 960, true);
                BufferedOutputStream bos = null;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(file));
                    bmp.compress(Bitmap.CompressFormat.JPEG, 75, bos);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        bos.flush();
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Intent intent = new Intent(SelectPictureNamecordActivity.this,
                        BucardRunner.class);
                intent.putExtra("path", selectPath);
                this.startActivity(intent);
                overridePendingTransition(zoomin, zoomout);
            }

        }
        if (requestCode == 8 && resultCode == RESULT_OK) {
            // 读识别返回值
            Bundle bun = data.getBundleExtra("GetRecogResult");
            Intent intent = new Intent(SelectPictureNamecordActivity.this, BucardRunner.class);
            intent.putExtra("RecogValue", bun);
            // intent.putExtra("camera", isAutoRecog);
            startActivity(intent);
            finish();
            overridePendingTransition(zoomin, zoomout);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return super.onTouchEvent(event);
    }

    protected String getLatestImage() {
        String latestImage = null;
        String[] items = {MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null,
                null, MediaStore.Images.Media._ID + " desc");
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
                    .moveToNext()) {
                latestImage = cursor.getString(1);
                break;
            }
        }
        return latestImage;
    }

    @Override
    public void callData(ArrayList<HashMap<String, String>> list , String imagepath) {
        Intent intent = new Intent(this,NameCordKingActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data",list);
        bundle.putString("codes",codes);
        bundle.putString("imagepath",imagepath);
        bundle.putBoolean("kehuqx", kehuqx);
        bundle.putBoolean("contastqx", contastqx);
        intent.putExtra("DATA",bundle);
        startActivity(intent);

    }
}
